package com.tim.bos.service;

import java.util.Arrays;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tim.bos.entity.Sequence;
import com.tim.bos.repository.SequenceDao;


@Transactional(propagation=Propagation.REQUIRES_NEW)
@Service("sequenceService")
public class SequenceService {


	@Autowired private SequenceDao  sequenceDao;
	
	private String sequenceNumber = "common";

	
	public static final int COUNT_INCACHE=20;
	public static final int COUNT_CEILING=Integer.MAX_VALUE;
	
	private int curVal=-1;
	private int baseVal=-1;
	
	
    @PostConstruct
	public synchronized void  init(){
		 retrieve();
	}

	public synchronized String getNextVal(String stringformat, Object... args) {
		if (args == null) {
			args = new String[0];
		}
		Object[] params = Arrays.copyOf(args, args.length + 1);
		params[args.length] = this.getNextVal();
		return String.format(stringformat, params);
	}
	synchronized private String getNextVal() {
		this.curVal = this.curVal + 1;
		if ((this.curVal - this.baseVal) >= COUNT_INCACHE) {
			retrieve();
		}
		int temp = 1000000000 + curVal;
		return String.valueOf(temp).substring(1);
	}

	synchronized private void retrieve() {
		Sequence s = (Sequence) this.sequenceDao.findByNumber(this.sequenceNumber);// 应该
		this.curVal = s.getCurrentVal();
		this.baseVal = this.curVal;
		int temp = this.curVal + COUNT_INCACHE;
		if (temp > COUNT_CEILING) {
			temp = 0;
		}
		s.setCurrentVal(temp);
		this.sequenceDao.save(s);
	}
	

	
}
